<template>
  <div :style="panelSty">
    <el-popover
        placement="top"
        width="200"
        v-model="popoverVisible"
        :style="{ position: 'absolute', left: popoverPosition.x + 'px', top: popoverPosition.y + 'px' }"
    >
      <div class="mapping-charts-tips">
        <div class="tips-item">
          <div class="tips-marker">
            <span style="background-color:#9EAEFF"></span>Input:
          </div>
          <div class="tips-val">{{popoverInfo.mmt}}</div>
        </div>

        <div class="tips-item">
          <div class="tips-marker">
            <span style="background-color:#99d115"></span>不良数:
          </div>
          <div class="tips-val">{{ popoverInfo.qty }}</div>
        </div>

        <div class="tips-item" v-if="defectType === 'RATIO'">
          <div class="tips-marker">
            <span style="background-color:#99d115"></span>不良Ratio:
          </div>
          <div class="tips-val">{{popoverInfo.ratio }}%</div>
        </div>
      </div>
    </el-popover>

    <canvas ref="panelCanvasBg" class="fabric-panel"></canvas>

  </div>
</template>
<script>
import {fabric} from "fabric"

export default {
  props: {
    defectType: {
      type: String,
      default: 'RATIO',
    },
  },
  data() {
    return {
      popoverVisible: false,
      popoverPosition: {x: 0, y: 0},
      hoverPanelId: '',
      hoverRatio: 0,
      wrapWidth: 0,
      wrapHeight: 0,
      popoverInfo:{
        ratio:"",
        qty:"",
        mmt:""
      }
    }
  },
  computed: {
    panelSty() {
      return {
        left: 0,
        top: 0,
        border: '1px solid red',
        width: this.wrapWidth + "px",
        height: this.wrapHeight + "px",
      }
    }
  },
  methods: {
    setLayout(myPanel, PanelForB6) {
      if (!myPanel) {
        return
      }
      const width = myPanel.clientWidth
      const height = myPanel.clientHeight
      this.wrapWidth = width
      this.wrapHeight = height


      let {totalWidth, totalHeight, qpanelInfos} = PanelForB6
      let scale = width / totalWidth//画布数据和散点图内容区域比例
      this.wrapWidth = totalWidth * scale
      this.wrapHeight = totalHeight * scale
      let panelDom = this.$refs.panelCanvasBg
      const canvas = new fabric.Canvas(panelDom, {
        width: this.wrapWidth, // 画布宽度
        height: this.wrapHeight, // 画布高度
        backgroundColor: 'white', // 画布背景色
      })
      canvas.renderOnAddRemove = false // 关闭自动
      canvas.selection = false            // 禁用框选
      canvas.skipTargetFind = false       // 仍允许事件命中
      canvas.hoverCursor = 'pointer'      // 鼠标悬停时样式

      let objectsToAdd = []
      for (let it of qpanelInfos) {
        for (let it2 of it.panelInfos) {
          objectsToAdd.push(this.setRectTxtGroup(it2, totalWidth, totalHeight))
        }
        objectsToAdd.push(this.setRectTxtGroup(it, totalWidth, totalHeight, true))
      }
      canvas.add(...objectsToAdd)
      canvas.setZoom(scale)
    },
    setRectTxtGroup(it, totalWidth, totalHeight, isQ = false) {//大Q降低不透明度，扩大字体100px
      let {topLeftX, topLeftY, bottomRightX, bottomRightY, panelId} = it
      let width = Math.abs(bottomRightX - topLeftX)
      let height = Math.abs(bottomRightY - topLeftY)

      // 1. 限制字体大小的逻辑
      const minDim = Math.min(width, height);
      let calculatedFontSize = minDim * 0.5;//为Q时，缩放0.8倍，为panel时，缩小一半
      let scaleList = [{len: 3, scale: 0.8}, {len: 4, scale: 0.7}, {len: 5, scale: 0.6}, {len: 6, scale: 0.5}, {
        len: 7,
        scale: 0.4
      }, {len: 8, scale: 0.3}, {len: 9, scale: 0.3}, {len: 10, scale: 0.3}]
      if (panelId.length > 2) {
        let scaleItem = scaleList.find(item => item.len === panelId.length)
        calculatedFontSize = calculatedFontSize * scaleItem.scale
      }
      if (isQ) {
        let rect = new fabric.Rect({
          width,
          height,
          fill: '#fff',
          stroke: 'gray',        // 边框颜色
          strokeWidth: 0,
          originX: 'center',
          originY: 'center',
        })
        let text = new fabric.Text(panelId, {
          fontSize: calculatedFontSize,
          fill: '#000',
          originX: 'center',
          originY: 'center',
        })
        let group=new fabric.Group([rect, text], {
          left: totalWidth / 2 + topLeftX,
          top: totalHeight / 2 - topLeftY,
          originX: 'left',
          originY: 'top',
          opacity: 0.2,
          selectable: false, // 不允许选中/拖动
          evented: false,     // 可以响应鼠标事件
        })
        return group
      } else {
        let rect = new fabric.Rect({
          width,
          height,
          fill: '#fff',
          stroke: 'gray',        // 边框颜色
          strokeWidth: 1,
          originX: 'center',
          originY: 'center',
        })
// 用于按比例填充的矩形（从左向右填充）
        const rectFill = new fabric.Rect({
          width: width * it.fillPer, // 按比例设置宽度
          height: height,
          fill: '#B7DAFE',
          originX: 'left',         // 从左侧开始
          originY: 'center',
          left: -width / 2,        // 对齐到背景矩形左边（因为背景的 originX=center）
        });
        const ratioTxt = new fabric.Text(it.ratio + '%', {
          fontSize: 12,
          fill: '#000',
          originX: 'center',
          originY: 'center',
        })
        const text = new fabric.Text(panelId, {
          fontSize: 12,
          fill: '#000',
          originX: 'left',   // 左对齐
          originY: 'top',    // 顶部对齐
          left: -width / 2 + 2,  // 从矩形左上角稍微内缩2px
          top: -height / 2 + 2,
        })
        let group = new fabric.Group([rect, rectFill, text, ratioTxt], {
          left: totalWidth / 2 + topLeftX,
          top: totalHeight / 2 - topLeftY,
          originX: 'left',
          originY: 'top',
          selectable: false, // 不允许选中/拖动
          evented: true,     // 可以响应鼠标事件
          hoverCursor: 'pointer', // 鼠标样式
        })


        // 绑定事件
        group.on('mouseover', (opt) => {
          const { e } = opt; // Fabric 封装事件里带有原生事件 e
          this.popoverVisible = true
          this.hoverPanelId = panelId
          this.hoverRatio = it.ratio * 100
          for(let attr in this.popoverInfo){
            this.popoverInfo[attr] = it[attr]
          }

          // 鼠标位置（相对于视口）
          const mouseX = e.clientX
          const mouseY = e.clientY

          // 设置 Popover 出现位置（右侧 10px，下方 10px）
          this.popoverPosition = {
            x: mouseX + 10,
            y: mouseY + 10
          }
        })
        group.on('mouseout', () => {
          this.popoverVisible = false
        })
        return group
      }
    },
  },
}
</script>
<style lang="stylus">
.fabric-panel {
  position absolute;
  left 0
  top 0
}
.mapping-charts-tips {
  .tips-item {
    margin-bottom: 5px;
    width: 200px;
    display: flex;
    white-space nowrap
  }
  .tips-val{
    margin-left: auto;
  }

  .tips-marker {
    span {
      display: inline-block;
      margin-right: 5px;
      border-radius: 10px;
      width: 10px;
      height: 10px;
    }
  }
}
</style>